package com.whale.cloud.util.solr;

import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.Collection;
/** Created by maoweidong on 2017/7/13. */
@Log4j2
public class CloudSolrClient {

  private static org.apache.solr.client.solrj.impl.CloudSolrClient cloudSolrClient = null;
  private static Collection<String> zkhost_collection;

  private SolrProperties solrProperties;

  public void setSolrProperties(SolrProperties solrProperties) {
    this.solrProperties = solrProperties;
  }

  public org.apache.solr.client.solrj.impl.CloudSolrClient getCloudSolrClient(String collection) {
    zkhost_collection = new ArrayList<>();
    String[] zkHosts = solrProperties.getZkHost().split(",");
    for (int i = 0; i < zkHosts.length; i++) {
      zkhost_collection.add(zkHosts[i]);
    }
    //连接集群
    if (cloudSolrClient == null) {
      try {
        cloudSolrClient =
            new org.apache.solr.client.solrj.impl.CloudSolrClient(zkhost_collection, "/solr");
        cloudSolrClient.setDefaultCollection(collection);
        cloudSolrClient.setZkClientTimeout(solrProperties.getZkClientTimeout());
        cloudSolrClient.setZkConnectTimeout(solrProperties.getZkConnectTimeout());
        cloudSolrClient.connect();
      } catch (Exception e) {
        log.error("The URL of zkHost is not correct!");
        e.printStackTrace();
      }
    }
    return cloudSolrClient;
  }
}
